<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */


class UserAction extends HomeAction
{

    protected $user;
    

	public function _initialize()
	{
		
		parent::_initialize();

		$actions = array('pm', 'follow');
		if (in_array(ACTION_NAME, $actions))
		{
			if(empty($this->_user['user_id']))
			{
			    $this->redirect('Account/login');
			}
		}

		$userID = intval($_REQUEST['uid']);
		$user = $this->_User->find($userID);
		if (empty($user))
		{
			$this->error(L('user_not_existed'));
		}

		//浏览权限检查
		if ($this->_user['user_id'] != $user['user_id'] && !$this->_userGroup['allow_view_profile'])
		{
			$this->error(L('no_view_profile_perms'));
		}

		//用户权限检查
		$actions = array('confirmAccount', 'setting', 'profile', 'privacy', 'authentication');
		if (in_array(ACTION_NAME, $actions))
		{
    		if ($user['user_id'] != $this->_user['user_id'])
    		{
    			$this->error(L('no_perms_action'));
    		}
		}

		//图形数据统计
		vendor('FlashChart.open-flash-chart');
    	vendor('FlashChart.open-flash-chart-object');

    	$actions = array('activity', 'qa', 'network', 'recentVisitor');

		if (in_array(ACTION_NAME, $actions))
		{
    		$url = U('User/getSummaryData', array('uid' => $userID));
    		$summaryChart = open_flash_chart_object_str('chart', 285, 150, $url, WEB_PUBLIC_PATH, 0);
    		$this->assign('summaryChart', $summaryChart);

		    $user['perms'] = $this->_User->getShareSettings($this->_user['user_id'], $userID);
		}
		
		//最近访客
		$View = D('UserVisitorView');
		$limit = 14;
		$map = array('UserVisitor.user_id' => $user['user_id']);
		$recentVisitors = $View->where($map)->limit($limit)->select();
		$this->assign('recentVisitors', $recentVisitors);

		L('user_activity', sprintf(L('user_activity'), $user['username']));
		
		$seo = array(
			'title' => L('user_activity'),
			'keywords' => '',
			'description' => $user['about'],
		);
		$this->assign('seo', $seo);

		$user['profile_url'] = format_user_url($user['user_id'], $user['username']);
		$this->user = $user;
	}


	//用户主页
	public function activity()
	{
		
		$user = $this->user;

		if (!empty($this->_user['user_id']) && $this->_user['user_id'] != $user['user_id'])
		{
			//是否已关注此用户
			$Follow = D('UserFollow');
			$map = array(
				'source_user' => $this->_user['user_id'],
				'target_user' => $user['user_id'],
			);
			$follow = $Follow->where($map)->find();
			$user['follow_status'] = isset($follow['status']) ? intval($follow['status']) : 0;
			
			//记录来访者印迹
			$Visitor = D('UserVisitor');
			$Visitor->addVisitLog($user['user_id'], $this->_user['user_id']);	
		}

		$Activity = D('Activity');

		//用户积分等级动态
		$UserGroup = D('UserGroup');
		$group = F('cache_usergroup_'.$user['user_group']);
		$map   = array('point_lower' => array('gt', $group['point_higher']));
		$order = array('point_lower' => 'asc');
		$nextGroup = $UserGroup->where($map)->find();

		$weekPoints    = $Activity->userWeekPoints($user['user_id']);
		$upgradePoints = $nextGroup['point_lower'] - $user['point_count'];
		$user['group_name']  = $group['name'];
		$user['week_points'] = intval($weekPoints);
		$user['upgrade_points'] = intval($upgradePoints);

		//勋章
		$user['medals'] = array();
		$medal = explode(',', $user['medal']);
		if (!empty($medal))
		{
		    $medals = F('cache_medals');
		    foreach ($medals as $value)
	    	{
	    		if (in_array($value['medal_id'], $medal))
	    		{
	    			$user['medals'][] = $value;
	    		}
	    	}
		}

		//确认注册链接
		$confirm = $user['user_id'] == $this->_user['user_id'] && 4 == $user['user_group'] && 'by_user' == $this->_global['require_activation'];
		if($confirm)
		{
		    $auth = kg_auth_code($user['user_id'], 'encode');
		    $user['require_confirm'] = 1;
		    $user['account_confirm_link'] = U('Account/confirmAccount', array('auth' => $auth));
		}

		//已回答问题
    	$View = D('QuestionAnswerView');
    	$limit = 5;
    	$map = $order = array();
    	$map['Answer.poster_id'] = $user['user_id'];
    	$order['Question.question_id'] = 'desc';
    	$questions = $View->where($map)->order($order)->limit($limit)->select();

		//用户积分动态
		$activities = array();
		if ($user['user_id'] == $this->_user['user_id'])
		{
			$activities = $Activity->userActivities($user['user_id'], 10);
		}

		$this->assign('user', $user);
		$this->assign('questions', $questions);
		$this->assign('pagination', $pagination);
		$this->assign('activities', $activities);
		$this->display();
	}


	//用户问题以及答案
	public function qa()
	{
		
		import('ORG.Util.Page');
		
	    $user = $this->user;

	    $types = array('answered','team-answered','asked','starred','followed');
	    $type  = in_array($_REQUEST['type'], $types) ? $_REQUEST['type'] : 'answered';
	    $allowRemove = ($user['user_id'] == $this->_user['user_id']) && in_array($type, array('starred','followed'));

	    if ($this->isPost())
	    {
	        $Question = D('Question');
	        $mods = $_POST['mods'];

	        if (!empty($mods))
	        {
	            foreach ($mods as $value)
	            {
	                if ('starred' == $type)
        	        {
        	        	$Starred = M('StarredQuestion');
        	        	$where = array(
        	        	    'user_id' => $this->_user['user_id'],
        	        	    'question_id' => $value,
        	        	);
        	        	$Starred->where($where)->delete();
        	        	$Question->updateStarCount($value);
        	        }
        	        elseif ('followed' == $type)
        	        {
        	            $Watched = M('WatchedQuestion');
        	        	$where = array(
        	        	    'user_id' => $this->_user['user_id'],
        	        	    'question_id' => $value,
        	        	);
        	        	$Watched->where($where)->delete();
        	        	$Question->updateWatchCount($value);
        	        }
	            }
	        }
	        $this->redirect('User/qa', array('uid'=>$user['user_id'],'type'=>$type));
	    }

	    switch (strtolower($type))
	    {
	    	case 'answered':
				$View = D('QuestionAnswerView');
				$map = array('Answer.poster_id' => $user['user_id']);
				$order = array('Question.question_id' => 'desc');
				break;
			case 'team-answered':
				$TeamUser = D('TeamUser');
				$teams = $TeamUser->getUserTeamIDs($user['user_id']); 
				$View = D('QuestionAnswerView');
				$map = array('Answer.team_id' => array('in', $teams));
				$order = array('Question.question_id' => 'desc');
				break;
	    	case 'asked':
				$View = D('QuestionView');
				$map = array('poster_id' => $user['user_id']);
				$order = array('question_id' => 'desc');
				break;
	    	case 'starred':
				$View = D('QuestionStarView');
				$map = array('QuestionStar.user_id' => $user['user_id']);
				$order = array('question_id' => 'desc');
				break;
	    	case 'followed':
				$View = D('QuestionFollowView');
				$map = array('QuestionFollow.user_id' => $user['user_id']);
				$order = array('question_id' => 'desc');
				break;
	    }
	    
		$parameter  = '';
		$parameter .= '&uid='.$user['user_id'];
		$parameter .= '&type='.$type;

		$pageSize = 10;
		$total = $View->where($map)->count();
		$Page  = new Page($total, $pageSize);
		$Page->parameter = $parameter;
		$pagination = $Page->show();
		$questions  = $View->where($map)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();

		$this->assign('user', $user);
		$this->assign('type', $type);
		$this->assign('allowRemove', $allowRemove);
		$this->assign('questions', $questions);
		$this->assign('pagination', $pagination);
		$this->display();
	}


	//用户社交关系圈
	public function network()
	{
		
	    $user = $this->user;

        $order = array();
        $types = array('follower', 'following', 'block');
        $type = in_array($_REQUEST['type'], $types) ? $_REQUEST['type'] : 'follower';
	    $parameter = '';

	    $allowRemove = $user['user_id'] == $this->_user['user_id'];

	    if ($this->isPost())
	    {
	        $Follow = D('UserFollow');
	        $mods = $_POST['mods'];
	    	if (!empty($mods))
	    	{
	    		foreach ($mods as $value)
	    		{
	    			if ('follower' == $type)
	    			{
	    				$Follow->rmFollow($value, $this->_user['user_id']);
	    			}
	    			elseif ('following' == $type)
	    			{
	    			    $Follow->rmFollow($this->_user['user_id'], $value);
	    			}
	    			elseif ('block' == $type)
	    			{
	    			    $Follow->rmBlock($this->_user['user_id'], $value);
	    			}
	    		}
	    	}
	    	$this->redirect('User/network', array('uid'=>$user['user_id'],'type'=>$type));
	    }

		switch (strtolower($type))
		{
			case 'follower':
				$View = D('FollowerView');
				$map = array(
					'target_user' => $user['user_id'],
					'status' => 1,
				);
				break;
			case 'following':
				$View = D('FollowingView');
				$map = array(
					'source_user' => $user['user_id'],
					'status' => 1,
				);
				break;
			case 'block':
				$View = D('FollowingView');
				$map = array(
					'source_user' => $user['user_id'],
					'status' => -1,
				);
				break;
		}

		import('ORG.Util.Page');

		$pageSize = 30;
		$total = $View->where($map)->count();
		$Page  = new Page($total, $pageSize);
		$Page->parameter = $parameter;
		$pagination = $Page->show();
		$users = $View->where($map)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();

		$this->assign('pagination', $pagination);
		$this->assign('user', $user);
		$this->assign('type', $type);
		$this->assign('allowRemove', $allowRemove);
		$this->assign('users', $users);
		$this->display();
	}
	
	
	//最近访客
	public function recentVisitor()
	{
		
		$user = $this->user;
		
		import('ORG.Util.Page');
		
		$View = D('UserVisitorView');
		
		$parameter = '';
		$map = array('UserVisitor.user_id' => $user['user_id']);
		$order = array('create_time' => 'desc');
		
		$pageSize = 30;
		$total = $View->where($map)->count();
		$Page  = new Page($total, $pageSize);
		$Page->parameter = $parameter;
		$pagination = $Page->show();
		$recentVisitors = $View->where($map)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();

		$this->assign('user', $user);
		$this->assign('pagination', $pagination);
		$this->assign('recentVisitors', $recentVisitors);
		$this->display();
	}


	//用户设置
	public function setting()
	{
		
	    $user = $this->user;
	    $types = array('profile', 'privacy', 'authentication');
	    $type = in_array($_GET['type'], $types) ? $_GET['type'] : 'profile';

	    $Account = M('UserAccount');
	    $map = array('user_id' => $user['user_id']);
	    $providers = $Account->where($map)->select();
	    
	    $passwordExplain = 'password_'. $this->_global['pwd_complex'] .'_explain';	
    	L('password_explain', sprintf(L($passwordExplain), $this->_global['min_pwd_chars'], $this->_global['max_pwd_chars']));
    	
	    $this->assign('user', $user);
	    $this->assign('type', $type);
	    $this->assign('providers', $providers);
	    $this->assign('timezoneOptions', L('timezone_options'));
	    $this->assign('timezoneSelected', $user['timezone']);
	    $this->assign('themeOptions', get_site_themes());
	    $this->assign('themeSelected', $user['theme']);
	    $this->assign('langOptions', get_site_languages());
	    $this->assign('langSelected', $user['lang']);
	    $this->display();
	}


	//编辑用户资料
	public function profile()
	{
		
	    $user = $this->user;

		if ($this->isPost())
		{
			$_validate = array(
				array('website', 'url', '{%url_invalid}', 2),
				array('birthday', 'is_valid_date', '{%date_invalid}', 0, 'function'),
    		);
			$this->_User->setProperty('_validate', $_validate);
			if (!$this->_User->create())
			{
				$this->error($this->_User->getError());
			}

			$map  = array('user_id' => $user['user_id']);
			$data = array(
				'gender'    => intval($_POST['gender']),
				'theme'     => $_POST['theme'],
				'lang'      => $_POST['lang'],
				'invisible' => intval($_POST['invisible']),
				'timezone'  => $_POST['timezone'],
				'website'   => trim($_POST['website']),
				'location'  => trim($_POST['location']),
				'birthday'  => $_POST['birthday'],
				'about'     => trim($_POST['about']),
			);

			cookie('think_template', $data['theme']);
			cookie('think_language', $data['lang']);

			$this->assign('jumpUrl', $user['profile_url']);
		    $this->success($message);
		}
	}


	//编辑用户隐私设置
	public function privacy()
	{
		
		$user = $this->user;

		if ($this->isPost())
		{
			$data = array(
				'new_answer_alert'   => intval($_POST['new_answer_alert']),
				'best_answer_alert'  => intval($_POST['best_answer_alert']),
				'follow_ask_alert'   => intval($_POST['follow_ask_alert']),
				'new_follower_alert' => intval($_POST['new_follower_alert']),
				'new_comment_alert'  => intval($_POST['new_comment_alert']),
				'qa_activity'        => intval($_POST['qa_activity']),
				'network_activity'   => intval($_POST['network_activity']),
				'allow_follow'       => intval($_POST['allow_follow']),
				'allow_contact'      => intval($_POST['allow_contact']),
			);

			$where = array('user_id' => $user['user_id']);
			$this->_User->where($where)->save($data);

			$this->assign('jumpUrl', $user['profile_url']);
    		$this->success(L('user_profile_updated'));
		}
	}


	//添加/移出关注
	public function follow()
	{
		
	    $user = $this->user;

	    $Follow = D('UserFollow');

	    $types = array('add', 'remove', 'block', 'unblock');
        $type = in_array($_GET['type'], $types) ? $_GET['type'] : 'add';
        if ('add' == $type)
        {
            if(!$user['allow_follow'])
            {
                $this->error(L('user_refuse_follow'));
            }

            if (exceed_follow_limit($this->_user['user_id'], $this->_user['user_group']))
            {
            	$this->error(L('exceed_follow_limit'));
            }

            $Follow->addFollow($this->_user['user_id'], $user['user_id']);

            //新粉丝通知
            if ($user['new_follower_alert'])
            {
                import('ORG.Net.Http');
                $requestUrl = get_site_domain() . U('Notification/newFollowerAlert', array('source_id'=>$this->_user['user_id'],'target_id'=>$user['user_id']));
                Http::async_request($requestUrl);
            }
        }
        elseif ('remove' == $type)
        {
            $Follow->rmFollow($this->_user['user_id'], $user['user_id']);
        }
        elseif ('block' == $type)
        {
            $Follow->addBlock($this->_user['user_id'], $user['user_id']);
        }
        elseif ('unblock' == $type)
        {
            $Follow->rmBlock($this->_user['user_id'], $user['user_id']);
        }

        redirect($user['profile_url']);
	}


	//用户间私信
	public function pm()
	{
		
	    $user = $this->user;

        $captcha = require_captcha_when('email', $this->_user['user_group']);

        if ($this->isPost())
		{
		    if (!$user['allow_contact'])
    		{
    			$this->error(L('user_refuse_contact'));
    		}

    		//邮件发送限制检查
            if (exceed_activity_limit($this->_user['user_id'], $this->_user['user_group'], 'email'))
            {
                $this->error(L('exceed_email_limit'));
            }

			//验证码检查
    		if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
    		{
    			$this->error(L('captcha_incorrect'));
    		}

            if (empty($_POST['subject']))
			{
				$this->error(L('msg_subject_required'));
			}

			if (empty($_POST['message']))
			{
				$this->error(L('msg_content_required'));
			}

			$subject = trim($_POST['subject']);
			$message = trim($_POST['message']);

			$Mailer = A('Mailer');
			$result = $Mailer->pm($this->_user['user_id'], $user['user_id'], $subject, $message);
			if ($result)
			{
			    $this->_User->logActivity($this->_user['user_id'],'email', 0, 0);
				$this->success(L('send_pm_ok'));
			}
			else
			{
			 	$this->error(L('send_pm_failed'));
			}
		}
		else
		{
			$this->assign('user', $user);
			$this->assign('captcha', $captcha);
			$html = $this->fetch();
			exit($html);
		}
	}


	//帐号重确认
	public function confirmAccount()
	{
		
	    $user = $this->user;
	    
	    if ($this->_user['user_id'] == $user['user_id'])
	    {
	        $Mailer = A('Mailer');
	        $result = $Mailer->confirmAccount($user['user_id']);
	        if ($result)
	        {
	            $this->assign('jumpUrl', $user['profile_url']);
	        	$this->success(L('send_account_confirm_email_ok'));
	        }
	        else
	        {
	            $this->error(L('send_email_failed'));
	        }
	    }
	}


	//数据走势
	public function statistics()
	{
		
	    $user = $this->user;

		$type = isset($_GET['type']) ? $_GET['type'] : 'point';
		$length = isset($_GET['length']) ? $_GET['length'] : 'week';

		$url = U('User/getStatisticsData', array('uid' => $user['user_id'], 'type' => $type, 'length' => $length));
		$chart = open_flash_chart_object_str('chart', '100%', '250', $url, WEB_PUBLIC_PATH, 0);

		$this->assign('user', $user);
		$this->assign('chart', $chart);
		$this->display();
	}


	//数据走势
	public function getStatisticsData()
	{
		
	    $user = $this->user;

	    $type = isset($_GET['type']) ? $_GET['type'] : 'point';
		$length = isset($_GET['length']) ? $_GET['length'] : 'week';

		$now = time();
		$map = $order = array();
		switch ($length)
		{
			case 'week':
				$range = 7;
				$start = $now - 86400 * 7;
				break;
			case 'month':
				$range = 30;
				$start = $now - 86400 * 30;
				break;
			case '3month':
				$range = 90;
				$start = $now - 86400 * 90;
				break;
		}

		//日期数组初始化
		for ($i=1; $i<=$range; $i++)
		{
			$date = date('m-d', $start + 86400 * $i);
			$data[$date] = 0;
		}

		if ('point' == $type)
		{
			$map = array(
				'user_id' => $user['user_id'],
				'create_time' => array('between', array($start, $now)),
			);
			$Model = M('Activity');
			$field = array('create_time','point');
			$results = $Model->field($field)->where($map)->select();
			if ($results)
			{
				foreach ($results as $value)
				{
					$date = date('m-d', $value['create_time']);
					$data[$date] += $value['point'];
				}
			}
			$line_label = L('point_count');
		}
		elseif ('answer' == $type)
		{
			$map = array(
				'poster_id' => $user['user_id'],
				'create_time' => array('between', array($start, $now)),
			);
			$Model = M('Answer');
			$results = $Model->where($map)->select();
			if ($results)
			{
				foreach ($results as $value)
				{
					$date = date('m-d', $value['create_time']);
					$data[$date] += 1;
				}
			}
			$line_label = L('answer_count');
		}
		elseif ('question' == $type)
		{
			$map = array(
				'poster_id' => $user['user_id'],
				'create_time' => array('between', array($start, $now)),
			);
			$Model = M('Question');
			$results = $Model->where($map)->select();
			if ($results)
			{
				foreach ($results as $value)
				{
					$date = date('m-d', $value['create_time']);
					$data[$date] += 1;
				}
			}
			$line_label = L('question_count');
		}
		elseif ('comment' == $type)
		{
			$map = array(
				'poster_id' => $user['user_id'],
				'create_time' => array('between', array($start, $now)),
			);
			$Model = M('Comment');
			$results = $Model->where($map)->select();
			if ($results)
			{
				foreach ($results as $value)
				{
					$date = date('m-d', $value['create_time']);
					$data[$date] += 1;
				}
			}
			$line_label = L('comment_count');
		}

		$title = L('user_statistics');
		$min = min($data);
		$max = kg_ceil_10(max($data));
		$x_label_steps = $range>10 ? ceil($range/10) : 1;
		$y_label_steps = 10;

		$g = new graph();
		$g->set_bg_colour('#F0F8E6');
		$g->set_data($data);
		$g->line_dot(2, 5, '#98CC61', $line_label, 20);
		$g->set_x_labels(array_keys($data));
		$g->set_x_label_style(10, '0x000000', 0, $x_label_steps);
		$g->y_label_steps($y_label_steps);

		if ($min < 0)
		{
			$min = 0 - kg_ceil_10(abs($min));
			$g->set_y_min($min);
		}
		$g->set_y_max($max);
		echo $g->render();
	}


	//图形统计所需数据
	public function getSummaryData()
	{
		
		$user = $this->user;

		$data = array(
			'answer' => $user['answer_count'],
			'question' => $user['question_count'],
			'comment' => $user['comment_count'],
		);

		$title = L('user_statistics');
		$max = kg_ceil_10(max($data));
		$bar = new bar(70, '#3BAE08');
		$bar->data = $data;

		$g = new graph();
		$g->title($title, '{padding:2px;font-size:16px;}');
		$g->set_bg_colour('#FFFFFF');
		$g->data_sets[] = $bar;
		$g->set_data($data);
		$g->set_x_labels(array_keys($data));
		$g->y_label_steps(1);
		$g->set_y_max($max);
		echo $g->render();
	}

}
//End Class

/* End of file UserAction.class.php */
/* Location: ./App/Lib/Action/Home/UserAction.class.php */